<template>
  <WidgetContainer :widget-id="config.id">
    <FormItemWidget :config="config" :rowIndex="rowIndex" :parentId="parentId" v-if="config.isFormItem">
      <component style="width: 100%;" :is="config.type" v-bind="config.attributes" @change="handleChange"
        v-model="fieldValue">
      </component>
    </FormItemWidget>
    <div v-else>
      <component style="width: 100%;" :is="config.type" v-bind="config.attributes" @change="handleChange"
        v-model="fieldValue">
      </component>
    </div>
  </WidgetContainer>
</template>

<script setup>
import { inject, onMounted } from 'vue'
import { executeEventHandler } from '@/utils/eventExecutor'
import { useFieldBinding } from '@/utils/useFieldBinding'

const formData = inject('formData')
const widgetList = inject('widgetList')

const props = defineProps({
  config: Object,
  rowIndex: Number,
  parentId: String
})

const { fieldValue } = useFieldBinding(formData, props.config, {
  rowIndex: props.rowIndex,
  parentId: props.parentId
})


onMounted(() => {
  executeEventHandler(props.config.events?.onMounted,
    { widgetConfig: props.config, formData: formData.value, widgetList: widgetList.value }
  )
})

const handleChange = (value) => {
  executeEventHandler(props.config.events?.onChange,
    { widgetConfig: props.config, formData: formData.value, widgetList: widgetList.value, value }
  )
}
</script>

<style scoped></style>